package gt

import (
	"fmt"

	"gitee.com/dark.H/gs"
	termbox "github.com/nsf/termbox-go"
)

const (
	K_CTRL_C = 3
	K_SPACE  = 32
	K_DEL    = 127
)

var (
	WindowSIZE = 10
)

type PanelInterface interface {
	OnKey(k termbox.Event) bool
	Draw()
}

func Renderbar(onrender func(width, row int)) {
	fmt.Print("\x1b7")       // 保存光标位置
	fmt.Print("\x1b[2k")     // 清除当前行内容
	defer fmt.Print("\x1b8") // 恢复光标位置
	onrender(gs.GetWindowsSize())
}

func OnSignal(before func(), doKey func(k termbox.Event) (ifbreak bool)) {
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	before()
Loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			switch ev.Key {
			case termbox.KeyEsc:
				// fmt.Println("You press Esc")
				// fmt.Println(ev)
				// time.Sleep(3 * time.Second)
				break Loop
			default:
				if doKey(ev) {
					break Loop
				}
			}
		}
	}
}

func SetOptionWindow(height int) {
	WindowSIZE = height
}

func ListTuiStart[T any](panel *ListPanel[T], onKey func(now int, selected T, key termbox.Event) bool) (one T) {
	Renderbar(func(width, row int) {
		OnSignal(func() {
			panel.Draw()
		}, panel.OnKey)

	})
	return
}

func AppStart(panel PanelInterface) {
	Renderbar(func(width, row int) {
		OnSignal(func() {
			panel.Draw()
		}, panel.OnKey)

	})
}
